﻿
/*********************************************************************************
--时间：2012-01-14 19:28:16
--作者：jjpeng
--邮箱：ling121211@gmail.com
--说明：json帮助类
 * 
 * 将 Json 字符串反序列化为对象时，键值对不必须是 Model 的所有属性都有，即只传部分属性也可以反序列化
 * 必须要保证属性大小写一致
--
*********************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;

using System.Data;

using Newtonsoft.Json;

namespace PCC.Framework.Utils
{
    /// <summary>
    /// 备注：Json字符串与对象之间的转换
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 将表转换为json字符串
        /// </summary>
        /// <param name="table">表</param>
        /// <returns></returns>
        public static string ToJson(DataTable table )
        {
            StringBuilder jsonBuilder = new System.Text.StringBuilder();
            if (table == null || table.Rows.Count == 0)
            {
                return string.Empty;
            }
            int rowCount = table.Rows.Count;
            int colCount = table.Columns.Count;
            for (int i = 0; i < rowCount; i++)
            {
                if (i == 0)
                {
                    jsonBuilder.Append("[");
                }
                jsonBuilder.Append("{");
                for (int j = 0; j < colCount; j++)
                {
                    ///需要考虑转义符、空值
                    jsonBuilder.Append("\"" + table.Columns[j].ColumnName + "\":\"" +  table.Rows[i][j].ToString().Replace("\"","\\\"").Replace("\r\n","\\r\\n") + "\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            return jsonBuilder.ToString().Trim();
        }

        /// <summary>
        /// 将表集合转换为json字符串
        /// </summary>
        /// <param name="ds">表集合</param>
        /// <returns></returns>
        public static string ToJson(DataSet ds)
        {
            string jsonString = string.Empty;
            if (ds == null || ds.Tables.Count == 0)
            {
                return string.Empty;
            }
            jsonString +="[";
            foreach (DataTable table in ds.Tables)
            {
                jsonString += ToJson(table);
                jsonString += ",";
            }
            jsonString = jsonString.Remove(jsonString.Length - 1, 1);
            jsonString +="]";
            return jsonString;
        }

        /// <summary>
        /// 将object对象转换为json字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson<T>(T obj)
        {
            string jsonStr = string.Empty;

            Type t = typeof(T);
            if (t.Name == "System.Data.DataTable")
            {
                jsonStr = ToJson(obj as DataTable);
            }
            else if (t.Name == "System.Data.DataSet")
            {
                jsonStr = ToJson(obj as DataSet);
            }
            else
            {
                jsonStr = JavaScriptConvert.SerializeObject(obj);
            }
            return jsonStr;
        }

        /// <summary>
        /// 将json字符串转换为类型参数指定的对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T FromJson<T>(string jsonStr) where T : new()
        {
            if (string.IsNullOrEmpty(jsonStr))
            {
                return new T();
            }
            return JavaScriptConvert.DeserializeObject<T>(jsonStr);
        }

        /// <summary>
        /// 将json字符串转换为object对象
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static object FromJson(string jsonStr)
        {
            if (string.IsNullOrEmpty(jsonStr))
            {
                return new object();
            }
            return JavaScriptConvert.DeserializeObject(jsonStr);
        }

    }
}
